package project.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import schronisko.Queries;


/**
 * Servlet implementation class Contact
 */
@WebServlet("/Contact")
public class Contact extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	static int ID_msg;
	Queries q = new Queries();
	HttpSession s;

	public Contact() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		s = request.getSession();
		PrintWriter out = response.getWriter();
		out.println("<link rel='stylesheet' type='text/css' href='styles/register.css'>");
		String topic = (String) request.getParameter("topic");
		String msg = (String) request.getParameter("msg");
		String captcha = (String)s.getAttribute("captcha");
		String captcha_typed = request.getParameter("code");
		response.setContentType("text/html");
		int viewed = 0;
		out.println("<div class='content'><center>");

		int ID_client = (Integer) s.getAttribute("ID");

		response.setContentType("text/html");
		int wynik = 0;
		if(request.getParameter("topic") != ""){
			if(request.getParameter("msg") != ""){
				if(captcha.equals(captcha_typed)){
					wynik = q.InsertMessage(ID_client, topic, msg, viewed);
					if(wynik == 1){
						out.println("Wiadomosc zostala wyslana<br>Prosze oczekiwac odpowiedzi w przeciagu 24 godzin<br>"
								+ "<a href=index.jsp>Powrot do strony glownej</a>");
						out.println("</center></div>");
						response.setHeader("Refresh", "2; URL=index.jsp");
					}
					else {
						s.setAttribute("contact_step", 1); // blad bazy danych
					}
				}
				else {
					s.setAttribute("contact_step", 4); // zly kod
				}
			}
			else{
				s.setAttribute("contact_step", 2); // brak tresci
			}
		}
		else{
			s.setAttribute("contact_step", 3); // brak tematu
		}
		if(wynik != 1){
			response.sendRedirect("Kontakt.jsp");
		}
	} 


}
